package com.ctg.behavior.calc.utils;

import org.apache.commons.lang3.StringUtils;

import com.ctg.behavior.calc.common.CtSQLConsts;
import com.ctg.behavior.calc.common.CtSQLParam;

public class CtCalcSQLUtils {

	public static boolean isEmptyCondtions(String sqlConditions) {
		if (StringUtils.isEmpty(sqlConditions)) {
			return true;
		}
		if (" (  ) ".equals(sqlConditions)) {
			return true;
		}
		if (" HAVING (  ) ".equals(sqlConditions)) {
			return true;
		}
		return false;
	}

	public static String fillEventAlias(String field, CtSQLParam sqlParam) {
		if (null == sqlParam) {
			return field;
		}
		String alias = sqlParam.getParam(CtSQLConsts.KEY_EVENT_ALIAS);
		if (StringUtils.isEmpty(alias)) {
			return field;
		}
		return alias + "." + field;
	}

	public static String fillUserAlias(String field, CtSQLParam sqlParam) {
		if (null == sqlParam) {
			return field;
		}
		String alias = sqlParam.getParam(CtSQLConsts.KEY_USER_ALIAS);
		if (StringUtils.isEmpty(alias)) {
			return field;
		}
		return alias + "." + field;
	}

	public static String fillAlias(String field, CtSQLParam sqlParam) {
		if (null == sqlParam) {
			return field;
		}
		String alias = sqlParam.getParam(CtSQLConsts.KEY_ALIAS);
		if (StringUtils.isEmpty(alias)) {
			return field;
		}
		return alias + "." + field;
	}

	public static String getAlias(CtSQLParam sqlParam) {
		if (null == sqlParam) {
			return "";
		}
		String alias = sqlParam.getParam(CtSQLConsts.KEY_ALIAS);
		if (StringUtils.isEmpty(alias)) {
			return "";
		}
		return alias;
	}

	/*************************************************
	 * 移除最外层的ORDER BY
	 * 
	 * @param sql
	 * @return
	 */
	public static String removeOrderBy(String sql) {
		if (null == sql) {
			return "";
		}
		int index = sql.lastIndexOf(")");
		if (index > 0) {
			index = sql.indexOf("ORDER", index);
		} else {
			index = sql.lastIndexOf("ORDER");
		}
		if (index > 0) {
			sql = sql.substring(index, index);
		}
		return sql;
	}

}
